var EventProxy = require('eventproxy');
var fs = require('fs')
var proxy = require('../proxy');
var Goods = proxy.Goods;
var config = require('../config').config


exports.goodslist = function(req, res){
    var me = req.params.currentUser;
    var factionId = req.params.factionId;
    Goods.findByFactionAndStatus(factionId, null, function(err, goodslist){
        res.render('goods/goodslist', {goodslist: goodslist, factionId: factionId});
    })
}

exports.setGoodsStatus = function(req, res){
    var me = req.params.currentUser;
    var ids = req.body.ids,
        status = req.body.status;
    var ep = new EventProxy();
    ep.after('setStatus', ids.length, function(resps){
        res.send({data: resps});
    })
    ep.bind('error', function(err){
        ep.unbind();
        res.send({error: err});
    });
    ids.forEach(function(id){
        _setStatus(status, id, ep);
    });
}

function _setStatus(status, id, ep){
    if(status === 'on'){
        Goods.onGoods(id, function(err, resp){
            if(err) return ep.emit('error', err);
            ep.emit('setStatus', resp);
        })
    }else if(status === 'off'){
        Goods.offGoods(id, function(err, resp){
            if(err) return ep.emit('error', err);
            ep.emit('setStatus', resp);
        })
    }else if(status === 'del'){
        Goods.delGoods(id, function(err, resp){
            if(err) return ep.emit('error', err);
            ep.emit('setStatus', resp);
        })
    }
}


exports.fetchGoods = function(req, res){
    var me = req.params.currentUser;
    var factionId = req.params.factionId;
    Goods.findByFactionAndStatus(factionId, 'on', function(err, goodslist){
        res.render('goods/goods_part',
            {goodslist: goodslist, factionId: factionId}, function(err, html){
            res.send(html);
        });
    })
}

exports.addGoods = function(req, res, next){
    var me = req.params.currentUser;
    var factionId = req.params.factionId;
    res.render('goods/addGoods', {factionId: factionId, me: me, goods: null});
}

exports.updateGoods = function(req, res, next){
    var me = req.params.currentUser;
    var id = req.params.id;
    Goods.findById(id, function(err, goods){
        res.render('goods/addGoods', {goods: goods, me: me, factionId: goods.belongFaction._id});
    })
}

exports.showGoods = function(req, res, next){
    var me = req.params.currentUser;
    var id = req.params.id;
    Goods.findById(id, function(err, goods){
        console.log(goods);
        res.render('goods/showGoods', {goods: goods, factionId: goods.belongFaction._id})
    })
}

exports.saveGoods = function(req, res, next){
    var me = req.params.currentUser;
    var factionId = req.body.factionId,
        name = req.body.name,
        description = req.body.description,
        price = req.body.price,
        count = req.body.count;
    var id = req.body.id;
    if(id){
        Goods.updateGoods(id, {
            name: name,
            description: description,
            price: price,
            count: count
        }, function(err, resp){
            if(err) return res.render('others/error', {error: err});
            var fileName = factionId+'_'+id+'.jpg'
            _saveGoodsImage(req.files.goodsImg, fileName, function(){
                res.redirect('/goodslist/'+factionId)
            });
        })
    }else{
        console.log('description-------'+description)
        Goods.newAndSave({
            name: name,
            description: description,
            price: price,
            count: count,
            factionId: factionId
        }, function(err, goods){
            if(err) return res.render('others/error', {error: err});
            var fileName = factionId+'_'+goods._id+'.jpg'
            _saveGoodsImage(req.files.goodsImg, fileName, function(){
                res.redirect('/goodslist/'+factionId)
            });
        })
    }
}

function _saveGoodsImage(file, fileName, callback){
    var contentType = file.headers['content-type'];
    if(file.originalFilename !== '' && contentType === 'image/jpeg'){
        var tempPath = file.path
        fs.readFile(tempPath, {}, function(err, buffer){
            fs.writeFile(config.app_root_dir + '/static/img/goods/'+fileName, buffer, {}, function(err, data){
                console.log('上传商品图片成功');
                callback()
            })
        })
    }else{
        console.log('非法图片');
        callback()
    }
}
